<?php

namespace Data;

class City extends Base {

	const CITY_ALL_KEY = 'city_all_key';

	const CITY_HAS_TOWNS = 'city_has_towns_hash';

	public function getCityAll() {
		$redis = $this->getRedis();
		$key = self::CITY_ALL_KEY;
		$data = $redis->get($key);
		if ($data) {
			return json_decode($data, true);
		}
		$result = $this->findAll();
		$data = array();
		foreach ($result as $v) {
			$data[$v['Code']] = $v['Name'];
		}
		$redis->set($key, json_encode($data));
		return $data;
	}

	public function getTowns($code) {
		$redis = $this->getRedis();
		$key = self::CITY_HAS_TOWNS;
		$data = $redis->hGet($key, $code);
		if ($data) {
			return json_decode($data, true);
		}
		$min = $code * 1000;
		$max = $min + 999;
		$data = array();
		$result = $this->from('Towns')->where(array('Code >=' => $min, 'Code <=' => $max))->findAll();
		foreach ($result as $v) {
			$data[$v['Code']] = $v['Name'];
		}
		$redis->hSet($key, $code, json_encode($data));
		return $data;
	}

	public function getCityByCodes($codes) {
		return $this->where(array('Code in' => $codes))->order('Code asc')->findAll();
	}

	public function getTownByCode($code) {
		return $this->from('Towns')->where(array('Code' => $code))->findOne();
	}
}